﻿using BySoft.Server.Business;
using BySoft.Server.Business.UserCode;
using BySoft.Server.Common;
using BySoft.Server.Common.Entity;
using BySoft.Server.Common.Enum;
using BySoft.Server.Consts;
using BySoft.Web.Utility;
using OneSoft.EntityCore;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace BySoft.Web.Site.Order
{
    public partial class OrderAdd : AuthBasePage
    {
        public DataTable OrderDetailDT
        {
            get
            {
                if (Session["OrderDetailDT"] == null)
                {
                    return CreateDetailDT();
                }
                else
                {
                    return (DataTable)Session["OrderDetailDT"];
                }
            }
            set
            {
                Session["OrderDetailDT"] = value;
            }
        }
        public DataTable CreateDetailDT()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("OrderNum");
            dt.Columns.Add("OrderDetailID");
            dt.Columns.Add("ProductID");
            dt.Columns.Add("ProductName");
            dt.Columns.Add("Unit");
            dt.Columns.Add("CustomerPartNo");
            dt.Columns.Add("Nums");
            dt.Columns.Add("Price");
            dt.Columns.Add("RMBPrice");
            dt.Columns.Add("Amount");
            dt.Columns.Add("TaxAmount");
            dt.Columns.Add("WorkOrderNo");
            dt.Columns.Add("IsFinish");
            dt.Columns.Add("IsNew");//是否新增
            dt.Columns.Add("IsDel");//是否删除
            return dt;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                OrderDetailDT = null;
                BindDDL();
            }
            cpBillDate.Value = DateTime.Now.ToString("yyyy-MM-dd");
            txtCustomerID.Attributes.Add("readonly", "true");
            txtCustomerName.Attributes.Add("readonly", "true");
            txtSendCustomerName.Attributes.Add("readonly", "true");
            txtAddr.Attributes.Add("readonly", "true");
            Master.ValidationGroup = "gSubmit";
            UIHelper.RunScript(this.Page, "iframeAutoFit();");
        }
        private void BindDDL()
        {
            BindParameterForListControl("Currency", ddlCurrency);
            UIHelper.InsertFirstItem(ddlCurrency);
        }

        protected void ddlCurrency_SelectedIndexChanged(object sender, EventArgs e)
        {
            string currency = this.ddlCurrency.SelectedValue;
            if (currency == CommonConsts.RMBCurrencyIndex)
            {
                TaxTr.Style.Remove("display");
            }
            else
            {
                TaxTr.Style.Add("display", "none");
                txtTaxRate.Text = "";
                chkIsTax.Checked = false;
            }
        }
        private void AddPro()
        {
            OrderDetailDT = GetAdd(OrderDetailDT);
        }
        private DataTable GetAdd(DataTable dt)
        {
            DataTable dttemp = dt.Copy();
            foreach (GridViewRow gvr in grdResult.Rows)
            {
                if (gvr.RowType == DataControlRowType.DataRow)
                {
                    Label lblOrderDetailID = (Label)gvr.FindControl("lblOrderDetailID");
                    Label lblOrderNum = (Label)gvr.FindControl("lblOrderNum");
                    Label lblProductID = (Label)gvr.FindControl("lblProductID");
                    Label lblProductName = (Label)gvr.FindControl("lblProductName");
                    Label lblUnit = (Label)gvr.FindControl("lblUnit");
                    TextBox txtCustomerPartNo = (TextBox)gvr.FindControl("txtCustomerPartNo");
                    TextBox txtNums = (TextBox)gvr.FindControl("txtNums");
                    TextBox txtPrice = (TextBox)gvr.FindControl("txtPrice");
                    TextBox txtRMBPrice = (TextBox)gvr.FindControl("txtRMBPrice");
                    TextBox txtAmount = (TextBox)gvr.FindControl("txtAmount");
                    TextBox txtTaxAmount = (TextBox)gvr.FindControl("txtTaxAmount");
                    TextBox txtWorkOrderNo = (TextBox)gvr.FindControl("txtWorkOrderNo");
                    CheckBox chkIsFinish = (CheckBox)gvr.FindControl("chkIsFinish");

                    string strProductID = CommonMethod.GetString(lblProductID.Text.Trim());


                    DataRow[] drs = dttemp.Select("ProductID='" + strProductID + "' ");
                    if (drs.Length > 0)
                    {
                        drs[0]["OrderDetailID"] = GetGridViewString(lblOrderDetailID);
                        drs[0]["OrderNum"] = GetGridViewString(lblOrderNum);
                        drs[0]["ProductID"] = GetGridViewString(lblProductID);
                        drs[0]["ProductName"] = GetGridViewString(lblProductName);
                        drs[0]["Unit"] = GetGridViewString(lblUnit);
                        drs[0]["CustomerPartNo"] = GetGridViewString(txtCustomerPartNo);
                        drs[0]["Nums"] = GetGridViewString(txtNums);
                        drs[0]["Price"] = GetGridViewString(txtPrice);
                        decimal amount = CommonMethod.ConvertToDecimal(txtNums.Text.Trim()) * CommonMethod.ConvertToDecimal(txtPrice.Text.Trim());
                        drs[0]["Amount"] = Math.Round(amount, 2).ToString();
                        if (ddlCurrency.SelectedValue.Equals(CommonConsts.RMBCurrencyIndex))//人民币
                        {
                            decimal taxrate = CommonMethod.ConvertToDecimal(txtTaxRate.Text.Trim()) / 100;
                            drs[0]["TaxAmount"] = Math.Round(amount * (1 + taxrate), 2).ToString();
                        }
                        else
                        {
                            drs[0]["TaxAmount"] = Math.Round(amount, 2).ToString();
                        }
                        drs[0]["RMBPrice"] = GetGridViewString(txtPrice);
                        drs[0]["WorkOrderNo"] = GetGridViewString(txtWorkOrderNo);
                        drs[0]["IsFinish"] = chkIsFinish.Checked ? "1" : "0";
                    }
                }
            }
            return dttemp;
        }

        private bool ValidateData()
        {
            AddPro();
            DataTable dtTemp = OrderDetailDT.Copy();
            if (dtTemp == null || dtTemp.Rows.Count <= 0)
            {
                UIHelper.AlertMessage(this.Page, "请添加明细！");
                return false;
            }
            return true;
        }

        protected void btnHidden_Click(object sender, EventArgs e)
        {
            BindData();
        }

        private void BindData()
        {
            DataView dv = new DataView(OrderDetailDT);
            dv.RowFilter = " IsDel <> '1' ";
            DataTable dt = dv.ToTable();
            if (dt != null && dt.Rows.Count > 0)
            {
                int index = 1;
                foreach (DataRow dr in dt.Rows)
                {
                    dr["OrderNum"] = index;
                    dr["WorkOrderNo"] = txtOrderID.Text.Trim() + index.ToString();
                    index++;
                }
                grdResult.DataSource = dt;
                grdResult.DataBind();
            }
            else
            {
                UIHelper.BindEmptyGridView(grdResult, dt);
            }
            UIHelper.RunScript(this.Page, "iframeAutoFit();");
        }
        protected void grdResult_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string strCode = e.CommandArgument.ToString();
            switch (e.CommandName)
            {
                case "del":
                    AddPro();
                    DataTable dt = OrderDetailDT.Copy();
                    DataRow[] dr = dt.Select("ProductID='" + strCode + "'");
                    if (dr != null && dr.Length > 0)
                    {
                        dr[0]["IsDel"] = "1";
                    }
                    OrderDetailDT = dt.Copy();
                    BindData();
                    UIHelper.AlertMessage(this.Page, Message.DeleteSuccess);
                    break;
                default:
                    break;
            }
        }

        protected void grdResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                ImageButton ibtn = (ImageButton)e.Row.FindControl("ibtnDel");
                Button btnDel = (Button)e.Row.FindControl("btnDel");
                CheckBox chkIsFinish = (CheckBox)e.Row.FindControl("chkIsFinish");
                if (ibtn != null)
                {
                    ibtn.OnClientClick = "ShowTopConfirm('提示信息','" + Message.ConfirmDelete + "','confirmCallback(\\'" + btnDel.ClientID + "\\')');return false;";
                }
                string strIsFinish = ((DataTable)((GridView)sender).DataSource).Rows[e.Row.RowIndex]["IsFinish"].ToString().Trim();
                if (!string.IsNullOrEmpty(strIsFinish) && strIsFinish == "1")
                {
                    chkIsFinish.Checked = true;
                }
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (!ValidateData())
            {
                return;
            }
            try
            {
                if (string.IsNullOrEmpty(CurrentUser.UserID))
                {
                    UIHelper.AlertMessage(this.Page, "等待时间太久，请重新填写！");
                    return;
                }
                if (!string.IsNullOrEmpty(this.txtOrderID.Text.Trim()) && !BsOrderBusiness.IsOrderIDExists(txtOrderID.Text.Trim()))
                {
                    BsOrderEntity entity = new BsOrderEntity();
                    entity.OrderID = GetString(txtOrderID);
                    entity.QuoteID = GetString(txtQuoteID);
                    entity.BillDate = GetDateTime(cpBillDate);
                    entity.OrderType = "X";
                    entity.CustomerID = GetString(txtCustomerID);
                    entity.ContactName = GetString(txtContactName);
                    entity.Mobile = GetString(txtMobile);
                    entity.SendCustomerID = GetString(hdSendCustomerID);
                    entity.SendContactName = GetString(txtSendContactName);
                    entity.SendMobile = GetString(txtSendMobile);
                    entity.DeliveryDate = GetDateTime(txtDeliveryDate);
                    entity.IsPreOrder = chkIsPreOrder.Checked ? "1" : "0";
                    entity.OfficialOrder = GetString(txtOfficialOrder);
                    entity.Currency = GetString(ddlCurrency);
                    if (entity.Currency.Equals(CommonConsts.RMBCurrencyIndex))
                    {
                        entity.IsTax = chkIsTax.Checked ? "1" : "0";
                        if (entity.IsTax.Equals("1"))
                        {
                            entity.TaxRate = GetDecimal(txtTaxRate);
                        }
                        else
                        {
                            entity.TaxRate = null;
                        }
                    }
                    else
                    {
                        entity.IsTax = "0";
                        entity.TaxRate = null;
                    }
                    entity.Status = "1";
                    entity.CreateDate = DateTime.Now;
                    entity.CreateUserID = CurrentUser.UserID;
                    entity.CreateUserName = CurrentUser.UserName;
                    entity.ModifyDate = DateTime.Now;
                    entity.ModifyUserID = CurrentUser.UserID;
                    entity.ModifyUserName = CurrentUser.UserName;

                    if (BsOrderBusiness.SaveOrUpdate(entity, OrderDetailDT, "Save"))
                    {
                        base.LogAction(BaseEnum.ActionType.Add, entity.OrderID, true, null, new EntityBase[] { entity });
                        UIHelper.AlertMessageGoToURL(this.Page, Message.SaveSuccess, "../Order/OrderList.aspx");
                    }
                    else
                    {
                        UIHelper.AlertMessage(this.Page, Message.SaveFail);
                    }
                }
                else
                {
                    UIHelper.AlertMessage(this.Page, "订单编号已存在,请重新输入！");
                    return;
                }
            }
            catch (Exception ex)
            {
                UIHelper.AlertMessage(this.Page, FomatString(ex.Message.ToString()));
            }
        }

        protected void btnQuoteHidden_Click(object sender, EventArgs e)
        {
            OrderDetailDT = null;
            string QuoteID = txtQuoteID.Text.Trim();
            if (!string.IsNullOrEmpty(QuoteID))
            {
                DataTable dt = BsQuoteBusiness.GetDataByID(QuoteID);
                if (dt != null && dt.Rows.Count > 0)
                {
                    DataTable dtemp = OrderDetailDT.Copy();
                    int index = 1;
                    foreach (DataRow drow in dt.Rows)
                    {
                        DataRow d = dtemp.NewRow();
                        d["OrderNum"] = CommonMethod.GetString(drow["OrderNum"]);
                        d["OrderDetailID"] = "";
                        d["ProductID"] = CommonMethod.GetString(drow["ProductID"]);
                        d["ProductName"] = CommonMethod.GetString(drow["ProductName"]);
                        d["Unit"] = CommonMethod.GetString(drow["Unit"]);
                        d["CustomerPartNo"] = CommonMethod.GetString(drow["CustomerPartNo"]);
                        d["Nums"] = CommonMethod.GetString(drow["Nums"]);
                        d["Price"] = CommonMethod.GetString(drow["Price"]);
                        d["Amount"] = CommonMethod.GetString(drow["Amount"]);
                        if (ddlCurrency.SelectedValue.Equals(CommonConsts.RMBCurrencyIndex))//人民币
                        {
                            decimal amount = CommonMethod.ConvertToDecimal(drow["Amount"]);
                            decimal taxrate = CommonMethod.ConvertToDecimal(txtTaxRate.Text.Trim()) / 100;
                            d["TaxAmount"] = Math.Round(amount * (1 + taxrate), 2).ToString();
                        }
                        else
                        {
                            d["TaxAmount"] = CommonMethod.GetString(drow["Amount"]);
                        }
                        d["RMBPrice"] = CommonMethod.GetString(drow["Price"]);
                        d["WorkOrderNo"] = "";
                        d["IsFinish"] = "0";
                        d["IsNew"] = "1";
                        d["IsDel"] = "-1";
                        dtemp.Rows.Add(d);
                        index++;
                    }
                    OrderDetailDT = dtemp.Copy();
                }
            }
            BindData();
        }
    }
}